package models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.Directory;

public class DirectoryModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "directory_";
	
	private static DirectoryModel instance = null;
	
	public static DirectoryModel getInstance() {
		if (instance == null) {
			instance = new DirectoryModel();
		}
		
		return instance;
	}
	
	private DirectoryModel() {
		try {
			ObjectifyService.register(Directory.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public void insert(Directory directory) {
		ofy.put(directory);
	}
	
	public Directory get(String id) {
		Directory directory = new Directory();
		try {
			directory = ofy.get(new Key<Directory>(Directory.class, id));
			if (cache != null) {
				cache.put(prefix + id, directory);
			}
		} catch (Exception e) {
			directory = null;
		}
		return directory;
	}
	
	public void insert(String domain) {
		boolean update = false;
		String character = domain.substring(0, 1).toLowerCase();
		
		Directory directory = get(character);
		
		if (directory == null) {
			
			directory = new Directory();
			directory.setId(character);
		}
		
		List<String> domains = directory.getDomains();
		if (domains.size() < directory.getLimit()) {
			if (!domains.contains(domain)) {
				domains.add(domain);
				directory.setDomains(domains);
				update = true;
			}
		}
		
		if (update) {
			insert(directory);
		}
		
	}
	
	
	
	public void delete(Directory directory) {
		ofy.delete(directory);
	}
}
